// ignore: implementation_imports, import_of_legacy_library_into_null_safe
import 'package:build/src/builder/build_step.dart';
import 'package:analyzer/dart/element/element.dart' as ele;

// ignore: import_of_legacy_library_into_null_safe
import 'package:source_gen/source_gen.dart';

// ignore: import_of_legacy_library_into_null_safe
import 'package:build/build.dart';
import 'package:xanno/src/anno/utils/pars_params.dart';
import 'utils/iconfont_util.dart';
import 'dart:io';
import 'iconfont.dart';

//import 'tpl/tpl.dart' as tpl;
import 'tpl/tpl_anim.dart' as tpl_anim;

class IconfontGenerator extends GeneratorForAnnotation<GIconfont> {
  final separator = Platform.pathSeparator;

  void _writeFile(String nameCode, String svgCase, Function tpl, String path) {
    String code = tpl(nameCode: nameCode, svgCase: svgCase);
    File(path)
      ..createSync(recursive: true)
      ..writeAsStringSync(code);
  }

  @override
  generateForAnnotatedElement(ele.Element element, ConstantReader annotation,
      BuildStep buildStep) async {
    final map = ParsParams.pars(annotation, {
      'enable': false,
      'url': '',
      'prefix': '',
      'dir': '',
      'name': '',
      'suffix': ''
    });
    bool enable = map['enable'];
    String url = map['url'];
    String prefix = map['prefix'];
    String dir = map['dir'];
    String name = map['name'];
    String suffix = map['suffix'];
    if (!enable) return null;

    String fileDir = dir.split('/').join(separator);
    String fileName = '$separator$name';
    String path = "${Directory.current.path}$separator$fileDir$fileName$suffix";

    if (url.isNotEmpty) {
//      if (animation) {
      List<ParsPathModel> parsPathList =
          await IconfontAnimUtil.read(url, prefix: prefix);
      if (parsPathList.isNotEmpty) {
        String nameCode = IconfontAnimUtil.buildIconName(parsPathList);
        String svgCase = IconfontAnimUtil.buildSvgCase(parsPathList);
        _writeFile(nameCode, svgCase, tpl_anim.clazzTpl, path);
      }
//      } else {
//        // 使用flutter_svg 第三方库
//        List<Map<String, dynamic>> svgList =
//            await IconfontUtil.parse2SvgList(url, prefix);
//        if (svgList.isNotEmpty) {
//          String nameCode = IconfontUtil.buildIconName(svgList);
//          String svgCase = IconfontUtil.buildSvgCase(svgList);
//          _writeFile(nameCode, svgCase, tpl.clazzTpl);
//        }
//      }
    }
    return null;
  }
}

Builder iconfontBuilder(BuilderOptions options) =>
    LibraryBuilder(IconfontGenerator(), generatedExtension: ".iconfont.dart");
